

local inspect = require "ddcl.inspect"
local tcp_request = require "ddcl.tcp_request"
local utils = require "ddcl.http.utils"

local function get_request_str(M, method, uri, header, body)
    local first
    first = string.format("%s %s HTTP/1.1", method, uri)
    local head_host
    if M.port == 80 then
        head_host = string.format("Host:%s", M.host)
    else
        head_host = string.format("Host:%s:%s", M.host, M.port)
    end

    local head = {
        first,
        head_host,
    }
    if M.keep_alive then
        table.insert(head, "Connection:keep-alive")
    end

    for i, v in ipairs(header) do
        table.insert(head, v)
    end
    if method == "POST" then
        table.insert(head, string.format("Content-Length: %d", string.len(body)))
        table.insert(head, "")
        table.insert(head, body)
    else
        table.insert(head, "\r\n")
    end
    return table.concat(head, "\r\n")
end

local function response_fn(request, channel)
    return utils.read_response(channel, 20480)
end

return function(opt)
    local M = {
        host = opt.host,
        port = opt.port,
        forward = opt.forward and true or false,
        keep_alive = opt.keep_alive and true or false,
    }
    M.request = tcp_request.queue(M)

    function M.post(uri, header, body)
        local str = get_request_str(M, "POST", uri, header or {}, body or "")
        local rsp = M.request.request(str, response_fn)
        M.request.close()
        return rsp
    end

    function M.get(uri, header, body)
        local str = get_request_str(M, "GET", uri, header or {}, body or "")
        local rsp = M.request.request(str, response_fn)
        M.request.close()
        return rsp
    end

    return M
end


